﻿using CzJ_VoteSys.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CzJ_VoteSys.Filters
{
    public class GlobalRESTfulActionFilter : IResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (!(context.Result is ObjectResult objectResult)) return;

            if (objectResult.Value is ApiResponse<object>) return;

            var apiResponse = new ApiResponse<object>
            {
                Code = objectResult.StatusCode switch
                {
                    StatusCodes.Status200OK => 0,
                    _ => -1 // 默认错误码
                },
                Msg = objectResult.StatusCode switch
                {
                    StatusCodes.Status200OK => "",
                    _ => "Unknown Error" // 默认错误消息  
                },
                Data = objectResult.Value
            };

            // 只要不是异常，都返回200
            context.Result = new ObjectResult(apiResponse)
            {
                StatusCode = 200
            };
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {

        }
    }
}
